<template>
  <div class="shop_main">
    <el-card>
      <el-form ref="formRef" :model="form" style="width: 100%">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="form.name" style="width: 100%" placeholder="请输入商品名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品类型" prop="typeName">
              <el-input v-model="form.typeName" style="width: 100%" placeholder="请输入商品类型"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品规格" prop="sku">
              <el-input v-model="form.sku" style="width: 100%" placeholder="请输入商品规格"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品条形码" prop="code">
              <el-input v-model="form.code" style="width: 100%" placeholder="请输入商品条形码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否出库" prop="isExport">
              <el-select
                v-model="form.isExport"
                placeholder="请选择是否出库"
                style="width: 100%"
                :disabled="isSelection"
              >
                <el-option label="已出库" value="1"></el-option>
                <el-option label="未出库" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建时间" prop="createTime">
              <el-date-picker
                v-model="form.createTime"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="" prop="name">
              <el-button :icon="Search" type="primary" @click="search">查 询</el-button>
              <el-button :icon="Refresh" @click="reset">重 置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    &nbsp;
    <el-card>
      <el-col :span="24">
        <el-button :icon="Plus" type="primary" @click="openEdit">新 增</el-button>
        <el-button v-if="!isSelection" :icon="Van" type="primary" @click="outboundShipments">商品出库</el-button>
        <el-button v-if="isSelection" :icon="CircleCheck" type="success" @click="openExport">确认出库</el-button>
        <el-button v-if="isSelection" :icon="CircleClose" @click="closeOutboundShipments">取消出库</el-button>
      </el-col>
      &nbsp;
      <el-table
        ref="multipleTable"
        :row-key="row => row.id"
        :data="tableData"
        style="width: 100%"
        align="center"
        border
        @select="handleSelect"
        @select-all="handleSelectAll"
      >
        <el-table-column v-if="isSelection" type="selection" width="55" :selectable="selectable" />
        <el-table-column prop="name" label="商品名称" align="center">
          <template #default="{ row }">
            <el-button link type="primary" @click="openDetail(row)">{{ row.name }}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="sku" label="商品规格" align="center">
          <template #default="{ row }">
            {{ row.sku || '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="typeName" label="商品类型" align="center"></el-table-column>
        <el-table-column
          prop="code"
          label="商品条形码"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
        <template #default="{ row }">
          {{ row.code || '--' }}
        </template>
      </el-table-column>
        <el-table-column prop="isExport" label="是否出库" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.isExport * 1" type="danger">已出库</el-tag>
            <el-tag v-else>未出库</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="transfer" label="快递单号" min-width="90" show-overflow-tooltip align="center">
          <template #default="{ row }">
            {{ row.transfer || '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="memo" label="备注" align="center">
          <template #default="{ row }">
            {{ row.memo || '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" width="170" label="创建时间" align="center">
          <template #default="{ row }">
            {{ formattedDateTime(row.createTime) || '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="exportTime" width="170" label="出库时间" align="center">
          <template #default="{ row }">
            {{ formattedDateTime(row.exportTime) || '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="action" label="操作" width="160" fixed="right" align="center">
          <template #default="{ row }">
            <el-button v-if="!(row.isExport * 1)" link type="primary" :icon="EditPen" @click="openEdit(row)">
              编辑
            </el-button>
            <el-button v-if="row.isExport * 1" link type="primary" :icon="View" @click="openDetail(row)">
              详情
            </el-button>
            <el-button
              @click="delCallback(row.id)"
              v-if="!(row.isExport * 1)"
              link
              :icon="Delete"
              style="color: #f56c6c"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      &nbsp;
      <el-pagination
        style="display: flex; justify-content: flex-end"
        background
        :current-page="pagenation.page"
        :page-size="pagenation.limit"
        :total="pagenation.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </el-card>
    &nbsp;
    <Edit v-model="showEdit" :isDetail="isDetail" :info="currentEdit" @close="closeEdit" @reload="loadData" />
    <transfer v-model="showExport" :selectedRows="selectedRows" @callback="closeOutboundShipments"></transfer>
  </div>
</template>

<script setup>
  import { getShopPageList } from '@/server/shop';
  import { ref, onMounted, nextTick } from 'vue';
  import { Search, Refresh, Plus, EditPen, Delete, Van, CircleCheck, CircleClose, View } from '@element-plus/icons-vue';
  import Edit from './edit.vue';
  import transfer from './transfer.vue';
  import { useDateFomatter } from '@/hooks/formatter';
  import { deleteShop, shopReturn } from '@/server/shop';
  import { ElMessageBox, ElMessage } from 'element-plus';

  const { formattedDateTime } = useDateFomatter();
  const form = ref({
    name: '',
    type: '',
  });
  const formRef = ref(null);
  const pagenation = ref({
    page: 1,
    limit: 10,
    total: 0,
  });
  const tableData = ref([]); //表格数据
  const currentEdit = ref({});
  const multipleTable = ref(null); // 表格实例
  const selectedRows = ref([]); // 存储所有选中的行
  const isDetail = ref(false);
  const showEdit = ref(false);
  const showExport = ref(false);
  const isSelection = ref(false);

  const handleSizeChange = size => {
    pagenation.value.limit = size;
    loadData();
  };
  const handleCurrentChange = page => {
    pagenation.value.page = page;
    loadData();
  };

  /** 新增商品 */
  function openAdd() {
    currentEdit.value = {};
    showEdit.value = true;
    isDetail.value = false;
  }

  /** 编辑商品 */
  function openEdit(row) {
    currentEdit.value = row;
    showEdit.value = true;
    isDetail.value = false;
  }

  /** 商品出库 */
  function outboundShipments(row) {
    isSelection.value = true;
    search();
  }

  /** 单个选择行数据 */
  function handleSelect(selection, row) {
    const index = selectedRows.value.findIndex(item => item.id === row.id);
    if (index === -1) {
      selectedRows.value.push(row);
    } else {
      selectedRows.value.splice(index, 1);
    }
  }

  /** 多选框数据回显 */
  function getDefaultSelectedRows() {
    tableData.value.forEach(item => {
      selectedRows.value.forEach(selected => {
        if (item.id === selected.id) {
          multipleTable.value.toggleRowSelection(item, true);
        }
      });
    });
  }

  /** 全选行数据 */
  function handleSelectAll(selection) {
    const currentPageIds = tableData.value.map(item => item.id);
    if (selection.length) {
      // 添加当前页未选中的行
      const newSelections = tableData.value.filter(
        item => !selectedRows.value.some(selected => selected.id === item.id),
      );
      selectedRows.value.push(...newSelections);
    } else {
      // 移除当前页已选中的行
      selectedRows.value = selectedRows.value.filter(item => !currentPageIds.includes(item.id));
    }
  }

  /** 取消出库 */
  function closeOutboundShipments() {
    isSelection.value = false;
    selectedRows.value = [];
    multipleTable.value.clearSelection();
    form.value.isExport = null;
    search();
  }

  // 只允许选择未出库的商品
  const selectable = row => {
    return row.isExport * 1 === 0;
  };

  /** 确认出库 */
  function openExport() {
    if (selectedRows.value.length <= 0) {
      ElMessage.warning('请至少选择一条数据');
      return;
    }
    showExport.value = true;
  }

  /** 商品详情 */
  function openDetail(row) {
    isDetail.value = true;
    showEdit.value = true;
    currentEdit.value = row;
  }

  function closeEdit() {
    showEdit.value = false;
  }

  /** 搜索 */
  function search() {
    loadData();
  }

  /** 重置 */
  function reset() {
    formRef.value.resetFields();
    loadData();
  }

  /** 删除商品 */
  function delCallback(id) {
    ElMessageBox.confirm('确认删除该商品吗？删除后不支持找回', '温馨提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
      customClass: 'custom-message-box',
      customStyle: { fontSize: '50px' },
    }).then(async () => {
      const res = await deleteShop({ id });
      if (res.code == 200) {
        ElMessage.success('操作成功');
        loadData();
      }
    });
  }

  /** 获取数据 */
  async function loadData() {
    if (isSelection.value) {
      form.value.isExport = '0';
    }
    const searchModel = { ...form.value, ...pagenation.value };
    if (form.value.createTime) {
      searchModel.startTime = form.value.createTime[0];
      searchModel.endTime = form.value.createTime[1];
    } else {
      delete searchModel.startTime;
      delete searchModel.endTime;
    }
    const res = await getShopPageList(searchModel);
    if (res.code === 200) {
      tableData.value = res.data.rows;
      pagenation.value.total = res.data.total;
      // 更新表格选中状态
      nextTick(() => {
        getDefaultSelectedRows();
      });
    }
  }

  onMounted(() => {
    loadData();
  });
</script>

<style scoped>
  ::v-deep(.el-form-item__label) {
    font-weight: 700;
  }

  .shop_main {
    width: 100%;
    height: 100%;
    position: relative;
  }
</style>
